/*
 * DCE400服务系统 -- 后端服务接口 -- DAO 标签
 * 包括：
 */
package dao

import (
	"errors"
	entity2 "gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"go.uber.org/zap"
	"strconv"
	"strings"
	"time"
)

//********************************************
//Func  ：查询标签列表，分页查询。
//Method：
//Usage ：
//********************************************
func QueryReceivedMsgList(page, pageSize int, receiverId int64, readFlag, msgType int) (int64, []*entity2.ReceivingMessage, error) {
	offset := (page - 1) * pageSize
	session := db.Session().Table("receiving_message")
	defer session.Close()

	if pageSize > 0 {
		session.Limit(pageSize, offset)
	}
	session = session.Where("receiver_id=?", receiverId)

	if readFlag > entity2.EReadFlag_All && readFlag <= entity2.EReadFlag_UnRead {
		session = session.And("read_flag = ?", readFlag)
	}
	if msgType > entity2.EMessageType_ToAll && msgType <= entity2.EMessageType_ToAdmin {
		session = session.And("read_flag = ?", msgType)
	}

	msgs := []*entity2.ReceivingMessage{}
	total, err := session.FindAndCount(&msgs)
	if err != nil {
		return 0, nil, err
	}
	return total, msgs, nil
}

//创建一个站内信给客户
func CreateMessageToCustomer(title, body, sendName string, senderId int64, receiverId []int64) (*entity2.Message, error) {

	var message entity2.Message
	message.MsgId = util.GenSnowflakeInt64()
	message.Body = body
	message.Title = strings.TrimSpace(title)
	message.Type = entity2.EMessageType_ToCustomer
	message.Sender = strings.TrimSpace(sendName)
	message.Status = 0
	if message.Sender == "" {
		message.Sender = "DCE400服务"
	}
	message.SenderId = senderId

	var idArray []string
	for _, id := range receiverId {
		idArray = append(idArray, strconv.FormatInt(id, 10))
	}
	message.ReceiverIdList = strings.Join(idArray, ";")

	cnt, err := db.Session().Table("message").Insert(&message)
	if err != nil {
		return nil, err
	}
	if cnt <= 0 {
		return nil, errors.New("insert num is 0")
	}
	return &message, err
}

//创建一个站内信给业务员
func CreateMessageToOperator(title, body, sendName string, senderId int64, receiverId []int64) (*entity2.Message, error) {

	var message entity2.Message
	message.MsgId = util.GenSnowflakeInt64()
	message.MsgId = util.GenSnowflakeInt64()
	message.Body = body
	message.Title = strings.TrimSpace(title)
	message.Type = entity2.EMessageType_ToOperator
	message.Sender = strings.TrimSpace(sendName)
	if message.Sender == "" {
		message.Sender = "DCE400服务"
	}
	message.SenderId = senderId
	message.Status = 0

	var idArray []string
	for _, id := range receiverId {
		idArray = append(idArray, strconv.FormatInt(id, 10))
	}
	message.ReceiverIdList = strings.Join(idArray, ";")

	cnt, err := db.Session().Table("message").Insert(&message)
	if err != nil {
		return nil, err
	}
	if cnt <= 0 {
		return nil, errors.New("insert num is 0")
	}
	return &message, err
}

//动作 action = 0新增
//    action = 1发送
//    action = 2删除
//    action = 3召回
func MessageSend(msgId int64, action int) error {
	if action == entity2.EMessageAction_Send { //发送
		//message 写入发送时间
		var message entity2.Message
		has, err := db.Session().Table("message").
			Where("msg_id=?", msgId).Get(&message)
		if err != nil {
			return err
		}
		if !has {
			return errors.New("no find this message")
		}
		if message.Status != 0 {
			return errors.New("status of message in draft") //不是草稿，不能重发
		}
		if message.ReceiverIdList == "" {
			return errors.New("receiver of message is empty") //接收人为空
		}

		message.Status = 1
		message.SendAt = time.Now()
		cnt, err := db.Session().Table("message").
			Where("msg_id=?", msgId).
			Cols("status,send_at"). //仅刷新状态和发送时间字段
			Update(message)
		if err != nil {
			global.Log.Error("MessageSend: update message failed.", zap.Any("error:", err))
		}
		if cnt <= 0 {
			global.Log.Error("MessageSend: update message count err.", zap.Any("count:", cnt))
		}

		session := db.Session().Table("receiving_message")
		defer session.Close()

		ReceiverIdList := strings.Split(message.ReceiverIdList, ",")
		for _, idStr := range ReceiverIdList {
			id, err := strconv.ParseInt(idStr, 10, 64)
			if err == nil {
				var receive entity2.ReceivingMessage
				receive.Id = util.GenSnowflakeInt64()
				receive.MsgId = msgId
				receive.ReceiverId = id //接收人
				receive.ReceiveAt = time.Now()
				receive.Type = message.Type
				receive.ReadFlag = 1 //未读
				cnt, err = session.Insert(&receive)
				if err != nil || cnt < 1 {
					global.Log.Error("MessageSend: insert receiving_message err.", zap.Any("count:", cnt), zap.Any("error:", err))
				} else {
					global.Log.Info("MessageSend: insert receiving_message success.", zap.Any("receiverId", idStr))
				}
			}
		}

	} else if action == entity2.EMessageAction_Delete { //删除草稿
		var message entity2.Message
		has, err := db.Session().Table("message").
			Where("msg_id=?", msgId).Get(&message)
		if err != nil {
			return err
		}
		if !has {
			return errors.New("no find this message")
		}
		message.Status = 2
		cnt, err := db.Session().Table("message").
			Where("msg_id=?", msgId).Cols("status"). //仅刷新状态
			Update(message)
		if err != nil || cnt < 1 {
			global.Log.Error("MessageSend: delete message err.", zap.Any("count:", cnt), zap.Any("error:", err))
		} else {
			global.Log.Info("MessageSend: delete message success.", zap.Any("messageId", msgId))
		}

	} else if action == entity2.EMessageAction_Recall { //召回
		//message_receiver删除这个msg的邮件
		var message entity2.Message
		has, err := db.Session().Table("message").
			Where("msg_id=?", msgId).Get(&message)
		if err != nil {
			return err
		}
		if !has {
			return errors.New("no find this message")
		}

		message.Status = 3
		message.SendAt = time.Now()
		cnt, err := db.Session().Table("message").
			Where("msg_id=?", msgId).
			Cols("status,send_at"). //仅刷新状态和发送时间字段
			Update(message)
		if err != nil {
			global.Log.Error("MessageSend: update message failed.", zap.Any("error:", err))
		}
		if cnt <= 0 {
			global.Log.Error("MessageSend: update message count err.", zap.Any("count:", cnt))
		}

		session := db.Session().Table("receiving_message")
		defer session.Close()
		cnt, err = session.Where("msg_id=?", msgId).Delete(&entity2.ReceivingMessage{})
		if err != nil {
			session.Rollback()
			return err
		}
		session.Commit()
		global.Log.Info("MessageSend: rcall message.", zap.Any("msgId:", msgId))
		return nil
	} else {
		return errors.New("unknow action for message")
	}
	return nil
}

//********************************************
//Func  ：查询数据库：指定工单的详情
//Method：GET
//Usage ：
//********************************************
func QueryMessageDetail(Id int64) (*entity2.ReceivingMessage, *entity2.Message, error) {
	//.Where("id=?",operatorId).Get(&operator)
	var receiveMsg entity2.ReceivingMessage
	var message entity2.Message
	has, err := db.Session().Table("receiving_message").Where("id=?", Id).Get(&receiveMsg)
	if err != nil || has == false {
		return nil, nil, err
	}

	if receiveMsg.MsgId > 0 {
		has, err = db.Session().Table("message").Where("id=?", Id).Get(&message)
		if has == false || err != nil {
			return &receiveMsg, nil, nil
		}
	}

	return &receiveMsg, &message, nil
}
